package com.example.demo.Service;

import Mapper.DateRecordMapper;
import entity.CDate;
import entity.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.Optional;

@Service
@Transactional
public class DateService {

    @Autowired
    private DateRecordMapper dateRecordMapper;


    //mysql事务
    //功能:在日历功能中，当选定日期的情绪未设置时插入新纪录。已经设置时更新新选择的情绪

    public void saveOrUpdateEmotionRecord(Long userId, LocalDate date, String emotion) {
        Optional<CDate> existingRecord = dateRecordMapper.findByUserIdAndDate(userId, date);
        if (existingRecord.isPresent()) {
            // 如果记录存在，更新情绪
            dateRecordMapper.updateEmotionRecord(userId, date, emotion);
        } else {
            // 如果记录不存在，插入新记录
            Long maxRecordId = dateRecordMapper.getMaxRecordId();
            Long newRecordId = (maxRecordId != null) ? maxRecordId + 1 : 1; // 如果表为空，从1开始
            dateRecordMapper.insertEmotionRecord(newRecordId, userId, date, emotion);
        }
    }
}